package com.xiaohudie.SSGworket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author xiao hu die
 * @Date 2022/3/27 18:35
 * @Version 1.0
 */
public class TcpTest02 {
    /**服务端*/
    public static void main(String[] args) {
        ServerSocket serverSocket =null;
        Socket socket =null;
        InputStream inputStream =null;
        ByteArrayOutputStream byteArrayOutputStream =null;
        try {
            serverSocket = new ServerSocket(8899);
            socket = serverSocket.accept();
             inputStream = socket.getInputStream();
             byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes =new byte[5];
            int len;
            while ((len=inputStream.read(bytes))!=-1){
                byteArrayOutputStream.write(bytes,0,len);
            }
            System.out.println(byteArrayOutputStream.toString());
            System.out.println(socket.getLocalAddress());
            System.out.println(socket.getLocalPort());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (byteArrayOutputStream!=null){
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
